﻿using DevComponents.DotNetBar;
using DevComponents.DotNetBar.SuperGrid;
using DevComponents.DotNetBar.SuperGrid.Style;
using Kimd.Common;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Kimd.Communication
{
    public partial class PlcDebugForm : OfficeForm
    {
        private PLCOperator _plc;
        public PlcDebugForm()
        {
            InitializeComponent();
            this.EnableGlass = false;
        }
        public PlcDebugForm(PLCOperator plc)
            : this()
        {
            this._plc = plc;
        }

        private void PlcDebugForm_Load(object sender, EventArgs e)
        {
            initGrid();
            addGrid();
        }
        private void initGrid()
        {
            string[] orderArray = EnumHelper.GetEnumDescriptions<RegisterType>().ToArray();
            if (_plc.Series.Equals("AM"))
                orderArray = new string[2] { "AM_QX", "AM_MW" };
            this.sGC_PLC.PrimaryGrid.Columns["地址区域"].EditorType = typeof(FragrantComboBox);
            this.sGC_PLC.PrimaryGrid.Columns["地址区域"].EditorParams = new object[] { orderArray };

            string[] orderArray2 = EnumHelper.GetEnumDescriptions<DataType>().ToArray();
            //if (_plc.Series.Equals("H5U"))
            //    orderArray2 = new string[2] { "H5U_M", "H5U_D" };
            this.sGC_PLC.PrimaryGrid.Columns["数据类型"].EditorType = typeof(FragrantComboBox);
            this.sGC_PLC.PrimaryGrid.Columns["数据类型"].EditorParams = new object[] { orderArray2 };

            //this.sGC_PLC.PrimaryGrid.Columns["读取"].EditorType = typeof(MyGridImageEditControl);
            //this.sGC_PLC.PrimaryGrid.Columns["读取"].EditorParams = new object[] { imageList1, ImageSizeMode.Zoom };

            //this.sGC_PLC.PrimaryGrid.Columns["写入"].EditorType = typeof(MyGridImageEditControl);
            //this.sGC_PLC.PrimaryGrid.Columns["写入"].EditorParams = new object[] { imageList1, ImageSizeMode.Zoom };

            //this.sGC_PLC.PrimaryGrid.Columns["删除"].EditorType = typeof(MyGridImageEditControl);
            //this.sGC_PLC.PrimaryGrid.Columns["删除"].EditorParams = new object[] { imageList1, ImageSizeMode.Zoom };
        }
        private void addGrid()
        {
            if (_plc != null && _plc.AddressShortcut != null)
            {
                foreach (var item in _plc.AddressShortcut)
                {
                    addNewRow(_plc.Series, item);
                }
            }
        }
        private void bI_Add_Click(object sender, EventArgs e)
        {
            addNewRow(_plc.Series);
        }
        private void addNewRow(string series, AddressInfo addressInfo = null)
        {
            if (addressInfo == null)
            {
                AddressInfo ai = new AddressInfo();

                GridRow row = new GridRow();
                row.Tag = ai;
                GridCell cell = new GridCell();
                cell.Value = getNewName();
                ai.AddressName = cell.Value.ToString();
                row.Cells.Add(cell);
                cell = new GridCell();
                if (series.Equals("AM"))
                    cell.Value = "AM_MW";
                if (series.Equals("H5U"))
                    cell.Value = "H5U_D";
                ai.RegisterType = EnumHelper.GetEnumValueFromDescription<RegisterType>(cell.Value.ToString());
                row.Cells.Add(cell);
                cell = new GridCell();
                cell.Value = "Bool";
                ai.DataType = EnumHelper.GetEnumValueFromDescription<DataType>(cell.Value.ToString());
                row.Cells.Add(cell);
                cell = new GridCell();
                cell.Value = "100";
                ai.StartAddress = Convert.ToInt32(cell.Value.ToString());
                row.Cells.Add(cell);
                cell = new GridCell();
                cell.Value = "1";
                ai.Length = Convert.ToInt32(cell.Value.ToString());
                row.Cells.Add(cell);
                cell = new GridCell();
                cell.Value = "0";
                cell.ReadOnly = true;
                row.Cells.Add(cell);
                cell = new GridCell();
                cell.Value = "true";
                row.Cells.Add(cell);
                cell = new GridCell();
                cell.Value = "";
                cell.ReadOnly = true;
                row.Cells.Add(cell);
                cell = new GridCell();
                cell.Value = "读取";
                cell.CellStyles.Default.TextColor = Color.White;
                row.Cells.Add(cell);
                cell = new GridCell();
                cell.CellStyles.Default.TextColor = Color.White;
                cell.Value = "写入";
                row.Cells.Add(cell);
                cell = new GridCell();
                cell.CellStyles.Default.TextColor = Color.White;
                cell.Value = "删除";
                row.Cells.Add(cell);

                this.sGC_PLC.PrimaryGrid.Rows.Add(row);
                this._plc.AddressShortcut.Add(ai);
            }
            else
            {
                GridRow row = new GridRow();
                row.Tag = addressInfo;
                GridCell cell = new GridCell();
                cell.Value = addressInfo.AddressName;
                row.Cells.Add(cell);
                cell = new GridCell();
                cell.Value = EnumHelper.GetEnumDescriptionFromValue(addressInfo.RegisterType);
                row.Cells.Add(cell);
                cell = new GridCell();
                cell.Value = EnumHelper.GetEnumDescriptionFromValue(addressInfo.DataType);
                row.Cells.Add(cell);
                cell = new GridCell();
                cell.Value = addressInfo.StartAddress;
                row.Cells.Add(cell);
                cell = new GridCell();
                cell.Value = addressInfo.Length;
                row.Cells.Add(cell);
                cell = new GridCell();
                cell.Value = "0";
                cell.ReadOnly = true;
                row.Cells.Add(cell);
                cell = new GridCell();
                if(addressInfo.DataType == DataType.Bool)
                    cell.Value = "true";
                else
                    cell.Value = "0";
                row.Cells.Add(cell);
                cell = new GridCell();
                cell.Value = "";
                cell.ReadOnly = true;
                row.Cells.Add(cell);
                cell = new GridCell();
                cell.Value = "读取";
                cell.CellStyles.Default.TextColor = Color.White;
                row.Cells.Add(cell);
                cell = new GridCell();
                cell.CellStyles.Default.TextColor = Color.White;
                cell.Value = "写入";
                row.Cells.Add(cell);
                cell = new GridCell();
                cell.CellStyles.Default.TextColor = Color.White;
                cell.Value = "删除";
                row.Cells.Add(cell);

                this.sGC_PLC.PrimaryGrid.Rows.Add(row);
            }
        }
        private string getNewName()
        {
            int index = 0;
            string tempName = $"Addr_{index}";
        label1:
            foreach (GridRow row in sGC_PLC.PrimaryGrid.Rows)
            {
                if (row.Cells[0].Value.ToString().Equals(tempName))
                {
                    index++;
                    tempName = $"Addr_{index}";
                    goto label1;
                }
            }
            return tempName;
        }

        private void sGC_PLC_CellValueChanged(object sender, GridCellValueChangedEventArgs e)
        {
            AddressInfo ai = e.GridCell.GridRow.Tag as AddressInfo;
            if (e.GridCell.GridColumn.Name.Equals("名称"))
            {
                ai.AddressName = e.GridCell.Value.ToString();
            }
            else if (e.GridCell.GridColumn.Name.Equals("地址类型"))
            {
                RegisterType rt = EnumHelper.GetEnumValueFromDescription<RegisterType>(e.GridCell.Value.ToString());
                ai.RegisterType = rt;
            }
            else if (e.GridCell.GridColumn.Name.Equals("数据类型"))
            {
                DataType dt = EnumHelper.GetEnumValueFromDescription<DataType>(e.GridCell.Value.ToString());
                if(dt == DataType.Bool)
                    e.GridCell.GridRow.Cells[6].Value = "true";
                else
                    e.GridCell.GridRow.Cells[6].Value = "0";
                ai.DataType = dt;
            }
            else if (e.GridCell.GridColumn.Name.Equals("起始地址"))
            {
                ai.StartAddress = Convert.ToInt32(e.GridCell.Value);
            }
            else if (e.GridCell.GridColumn.Name.Equals("长度"))
            {
                ai.Length = Convert.ToInt32(e.GridCell.Value);
            }
        }

        private void sGC_PLC_PostRenderCell(object sender, GridPostRenderCellEventArgs e)
        {
            if (e.GridCell.GridColumn.Name.Equals("读取"))
            {
                RenderButtonBackground(e);
            }
            else if (e.GridCell.GridColumn.Name.Equals("写入"))
            {
                RenderButtonBackground2(e);
            }
            else if (e.GridCell.GridColumn.Name.Equals("删除"))
            {
                RenderButtonBackground3(e);
            }
            else if (e.GridCell.GridColumn.Name.Equals("信息"))
            {
                RenderButtonBackground4(e);
            }
        }
        private void RenderButtonBackground(GridPostRenderCellEventArgs e)
        {
            if ((e.RenderParts & RenderParts.Background) == RenderParts.Background)
            {
                // Render a Red gradient background for
                // the slider if the cell Value is > 75

                if (e.GridCell.Value.ToString().Equals("读取"))
                {
                    Rectangle r = e.Bounds;

                    using (Brush br = new
                        LinearGradientBrush(r, Color.Transparent, Color.Orange, 90f))
                    {
                        r.X++;
                        r.Width--;

                        e.Graphics.FillRectangle(br, r);
                    }
                }
            }
        }
        private void RenderButtonBackground2(GridPostRenderCellEventArgs e)
        {
            if ((e.RenderParts & RenderParts.Background) == RenderParts.Background)
            {
                // Render a Red gradient background for
                // the slider if the cell Value is > 75

                if (e.GridCell.Value.ToString().Equals("写入"))
                {
                    Rectangle r = e.Bounds;

                    using (Brush br = new
                        LinearGradientBrush(r, Color.Transparent, Color.Lime, 90f))
                    {
                        r.X++;
                        r.Width--;

                        e.Graphics.FillRectangle(br, r);
                    }
                }
            }
        }
        private void RenderButtonBackground3(GridPostRenderCellEventArgs e)
        {
            if ((e.RenderParts & RenderParts.Background) == RenderParts.Background)
            {
                // Render a Red gradient background for
                // the slider if the cell Value is > 75

                if (e.GridCell.Value.ToString().Equals("删除"))
                {
                    Rectangle r = e.Bounds;

                    using (Brush br = new
                        LinearGradientBrush(r, Color.Transparent, Color.Red, 90f))
                    {
                        r.X++;
                        r.Width--;

                        e.Graphics.FillRectangle(br, r);
                    }
                }
            }
        }
        private void RenderButtonBackground4(GridPostRenderCellEventArgs e)
        {
            if ((e.RenderParts & RenderParts.Background) == RenderParts.Background)
            {
                // Render a Red gradient background for
                // the slider if the cell Value is > 75

                if (e.GridCell.Value.ToString().Contains("失败"))
                {
                    Rectangle r = e.Bounds;

                    using (Brush br = new
                        LinearGradientBrush(r, Color.Transparent, Color.OrangeRed, 45f))
                    {
                        r.X++;
                        r.Width--;

                        e.Graphics.FillRectangle(br, r);
                    }
                }
                else if (e.GridCell.Value.ToString().Contains("成功"))
                {
                    Rectangle r = e.Bounds;

                    using (Brush br = new
                        LinearGradientBrush(r, Color.Transparent, Color.ForestGreen, 45f))
                    {
                        r.X++;
                        r.Width--;

                        e.Graphics.FillRectangle(br, r);
                    }
                }
            }
        }

        private async void sGC_PLC_CellClick(object sender, GridCellClickEventArgs e)
        {
            if(e.GridCell.GridColumn.Name.Equals("读取"))
            {
                RegisterType rt = EnumHelper.GetEnumValueFromDescription<RegisterType>(e.GridCell.GridRow.Cells[1].Value.ToString());
                DataType dt = EnumHelper.GetEnumValueFromDescription<DataType>(e.GridCell.GridRow.Cells[2].Value.ToString());
                int startAddress = Convert.ToInt32(e.GridCell.GridRow.Cells[3].Value.ToString());
                int length = Convert.ToInt32(e.GridCell.GridRow.Cells[4].Value.ToString());
                e.GridCell.Value = "读取中...";
                await Task.Run(() =>
                {
                    List<string> vals;//= new List<string>();
                    int errCode = 0;
                    if (this._plc.Read(rt, dt, startAddress, length, out vals, out errCode))
                    {
                        e.GridCell.GridRow.Cells[5].Value = string.Join(",", vals);
                        e.GridCell.GridRow.Cells[7].Value = "读取成功";
                    }
                    else
                        e.GridCell.GridRow.Cells[7].Value = $"读取失败,错误代码{errCode}";
                    return true;
                });
                e.GridCell.Value = "读取";
            }
            else if(e.GridCell.GridColumn.Name.Equals("写入"))
            {
                RegisterType rt = EnumHelper.GetEnumValueFromDescription<RegisterType>(e.GridCell.GridRow.Cells[1].Value.ToString());
                DataType dt = EnumHelper.GetEnumValueFromDescription<DataType>(e.GridCell.GridRow.Cells[2].Value.ToString());
                int startAddress = Convert.ToInt32(e.GridCell.GridRow.Cells[3].Value.ToString());
                int length = Convert.ToInt32(e.GridCell.GridRow.Cells[4].Value.ToString());
                List<string> vals = new List<string>();
                if(dt == DataType.Bool)
                {
                    List<string> temp = e.GridCell.GridRow.Cells[6].Value.ToString().Split(',').ToList();
                    temp.ForEach(v => vals.Add(v.ToLower().Equals("true") ? "1" : "0"));
                }
                else
                    vals = e.GridCell.GridRow.Cells[6].Value.ToString().Split(',').ToList();
                await Task.Run(() =>
                {
                    int errCode = 0;
                    if (this._plc.Write(rt, dt, startAddress, vals, out errCode))
                    {
                        e.GridCell.GridRow.Cells[5].Value = string.Join(",", vals);
                        e.GridCell.GridRow.Cells[7].Value = "写入成功";
                    }
                    else
                        e.GridCell.GridRow.Cells[7].Value = $"写入失败,错误代码{errCode}";
                });
            }
        }

        private void bI_Import_Click(object sender, EventArgs e)
        {
        }
    }
    internal class FragrantComboBox : GridComboBoxExEditControl
    {
        public FragrantComboBox(IEnumerable orderArray)
        {
            DataSource = orderArray;
        }
    }
    internal class MyGridImageEditControl : GridImageEditControl
    {
        public MyGridImageEditControl(
            ImageList imageList, ImageSizeMode sizeMode)
        {
            ImageList = imageList;
            ImageSizeMode = sizeMode;
        }
    }
}
